package cn.china.myspringboot.interceptor;

import cn.china.myspringboot.config.JwtConfig;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;


@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器");

        if(RequestMethod.OPTIONS.name().equals(request.getMethod())){//放行post get delete put ...
            return  true;
        }

         //验证token是否生效
          if(request.getRequestURI().equals("/login")){//放行登录请求,只有登录成功才有token
              return  true;
          }

          //前端请求后端login登录,登录成功后,后端响应前端一个token,前端要保存这个token
          //以后前端请求时,都要给后端传token(token放在请求头header中),后端验证token是否合法

          //获取token
          String token=request.getHeader(jwtConfig.getHeader());//getHeader()的值就是"token"
           if(ObjectUtils.isEmpty(token)){//判断token是否为空
               throw new  SignatureException(jwtConfig.getHeader()+"不能为空");
           }

           //开始验证token的合法性(token是否过期)

        Claims claims=null;

        try {
            claims=jwtConfig.getTokenClaim(token);//获取Claims对象,用于验证token合法性
            if(claims==null||jwtConfig.isTokenExpired(claims.getExpiration())){//当前token不合法
                throw new  SignatureException(jwtConfig.getHeader()+"已失效");
            }
        }catch (Exception e){
            throw new  SignatureException(jwtConfig.getHeader()+"已失效");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
